package com.kujie.websocket.config;

import com.kujie.websocket.config.properties.WebSocketProperties;
import com.kujie.websocket.handler.AuthPrincipalHandler;
import com.kujie.websocket.handler.WebSocketDefaultFactory;
import com.kujie.websocket.listener.WebSocketTopicListener;
import com.kujie.websocket.service.IWebSocketMessageService;
import com.kujie.websocket.service.impl.WebSocketMessageServiceImpl;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory;
import org.springframework.web.socket.server.HandshakeHandler;

/**
 * @author sean.zhou
 * @version 0.1
 * @date 2021/11/17
 */
@ConditionalOnProperty(value = "websocket.enabled", havingValue = "true")
@EnableConfigurationProperties(WebSocketProperties.class)
@EnableWebSocketMessageBroker
@AutoConfiguration
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {



    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // Set the WebSocket connection address
        registry.addEndpoint("/api/v1/ws")
                .setAllowedOriginPatterns("*")
                .setHandshakeHandler(handshakeHandler());
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
        registry.addDecoratorFactory(webSocketHandlerDecoratorFactory());
    }


    @Bean
    public WebSocketHandlerDecoratorFactory webSocketHandlerDecoratorFactory() {
        return new WebSocketDefaultFactory();
    }


    @Bean
    public IWebSocketMessageService webSocketMessageService() {
        return new WebSocketMessageServiceImpl();
    }

    @Bean
    public HandshakeHandler handshakeHandler() {
        return new AuthPrincipalHandler();
    }

    @Bean
    public WebSocketTopicListener topicListener() {
        return new WebSocketTopicListener();
    }
}